<template>
  <div class="orders-container">
    <el-card class="header-card">
      <div class="header-content">
        <h1>My Orders</h1>
        <div class="order-stats">
          <el-tag type="info">Total Orders: {{ orders.length }}</el-tag>
          <el-tag type="success">Completed: {{ completedOrders }}</el-tag>
          <el-tag type="warning">Pending: {{ pendingOrders }}</el-tag>
        </div>
      </div>
    </el-card>

    <el-empty v-if="loading" description="Loading orders...">
      <el-skeleton :rows="3" animated />
    </el-empty>

    <el-empty v-else-if="orders.length === 0" description="No orders found">
      <el-button type="primary" @click="goToShop">Go Shopping</el-button>
    </el-empty>

    <div v-else class="orders-list">
      <el-collapse v-model="activeOrders" @change="handleOrderExpand">
        <el-collapse-item
            v-for="order in orders"
            :key="order.orderId"
            :name="order.orderId"
            class="order-item"
        >
          <template #title>
            <div class="order-header">
              <span class="order-id">Order #{{ order.orderId }}</span>
              <span class="order-date">{{ formatDate(order.createdAt) }}</span>
              <el-tag :type="order.orderStatus ? 'success' : 'warning'" size="small">
                {{ order.orderStatus ? 'Completed' : 'Pending' }}
              </el-tag>
              <span class="order-total">{{ formatPrice(order.totalPrice) }}</span>
            </div>
          </template>

          <div class="order-details">
            <div class="order-meta">
              <p><strong>Order Date:</strong> {{ formatDate(order.createdAt, true) }}</p>
              <p v-if="order.updatedAt"><strong>Last Updated:</strong> {{ formatDate(order.updatedAt, true) }}</p>
            </div>

            <el-divider content-position="center">Order Items</el-divider>

            <div v-if="orderItems[order.orderId] && !loadingItems[order.orderId]" class="order-items">
              <div class="product-cards">
                <el-card
                    v-for="item in orderItemsWithProducts[order.orderId]"
                    :key="item.orderItemId"
                    class="product-card"
                    shadow="hover"
                >
                  <div class="product-card-content">
                    <el-image
                        :src="item.product?.image_url || `/api/placeholder/120/120`"
                        fit="cover"
                        class="product-image"
                        :preview-src-list="item.product?.image_url ? [item.product.image_url] : []"
                    >
                      <template #error>
                        <div class="image-placeholder">
                          <el-icon><Picture /></el-icon>
                        </div>
                      </template>
                    </el-image>

                    <div class="product-details">
                      <h3 class="product-name">{{ item.product?.name || 'Product not available' }}</h3>
                      <p class="product-description">{{ truncateText(item.product?.description, 80) }}</p>

                      <div class="product-price-qty">
                        <div class="product-price">
                          <div class="unit-price">{{ formatPrice(item.product?.price) }} x {{ item.quantity }}</div>
                          <div class="subtotal">Subtotal: {{ formatPrice(calculateSubtotal(item)) }}</div>
                        </div>
                        <el-tag size="small" type="info" class="quantity-tag">
                          Qty: {{ item.quantity }}
                        </el-tag>
                      </div>
                    </div>
                  </div>
                </el-card>
              </div>
            </div>
            <div v-else-if="loadingItems[order.orderId]" class="loading-items">
              <el-skeleton :rows="2" animated />
            </div>

            <el-divider content-position="center">Order Summary</el-divider>

            <div class="order-summary">
              <div class="summary-row">
                <span>Total Items:</span>
                <span>{{ calculateTotalItems(order.orderId) }}</span>
              </div>
              <div class="summary-row total">
                <span>Total:</span>
                <span>{{ formatPrice(order.totalPrice) }}</span>
              </div>
            </div>

            <el-divider content-position="center">Actions</el-divider>

            <div class="order-actions">
              <el-button
                  type="danger"
                  :disabled="order.orderStatus"
                  @click.stop="cancelOrder(order.orderId)"
                  :loading="cancellingOrder === order.orderId"
              >
                Cancel Order
              </el-button>
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
  </div>
</template>

<script lang='ts'>
import { ref, computed, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Picture } from '@element-plus/icons-vue';
import type {Order} from "../../types.ts";

export default {
  name: 'OrdersView',
  components: {
    Picture
  },
  setup(props) {
    const orders = ref<Order[]>([]);
    const orderItems = ref({});
    const orderItemsWithProducts = ref({});
    const loading = ref<boolean>(true);
    const loadingItems = ref({});
    const activeOrders = ref<Order[]>([]);
    const cancellingOrder = ref(null);

    const completedOrders = computed(() => {
      return orders.value.filter(order => order.orderStatus).length;
    });

    const pendingOrders = computed(() => {
      return orders.value.filter(order => !order.orderStatus).length;
    });

    const fetchOrders = async () => {
      try {
        loading.value = true;
        const id=sessionStorage.getItem('userId');
        const response = await axios.get(`/api/order/customer/${id}/orders`);
        orders.value = response.data;

        // If we have orders, automatically expand the most recent one
        if (orders.value.length > 0) {
          activeOrders.value = [orders.value[0].orderId];
          await fetchOrderItems(orders.value[0].orderId);
        }
      } catch (error) {
        console.error('Error fetching orders:', error);
        ElMessage.error('Failed to load orders. Please try again later.');
      } finally {
        loading.value = false;
      }
    };

    const fetchOrderItems = async (orderId) => {
      try {
        loadingItems.value = { ...loadingItems.value, [orderId]: true };
        const response = await axios.get(`/api/order/items?orderIds=${orderId}`);
        orderItems.value = {
          ...orderItems.value,
          [orderId]: response.data
        };

        // Initialize product data structure
        orderItemsWithProducts.value[orderId] = [];

        // Fetch product details for each order item
        await Promise.all(response.data.map(async (item) => {
          const productData = await fetchProductDetails(item.productId);
          orderItemsWithProducts.value[orderId].push({
            ...item,
            product: productData
          });
        }));
      } catch (error) {
        console.error('Error fetching order items:', error);
        ElMessage.error('Failed to load order items. Please try again later.');
      } finally {
        loadingItems.value = { ...loadingItems.value, [orderId]: false };
      }
    };

    const fetchProductDetails = async (productId) => {
      try {
        const response = await axios.get(`/api/product/${productId}`);
        return response.data;
      } catch (error) {
        console.error(`Error fetching product details for ID ${productId}:`, error);
        return null;
      }
    };

    const handleOrderExpand = (expandedOrderIds) => {
      expandedOrderIds.forEach(orderId => {
        if (!orderItems.value[orderId]) {
          fetchOrderItems(orderId);
        }
      });
    };

    const cancelOrder = async (orderId) => {
      try {
        await ElMessageBox.confirm(
            'Are you sure you want to cancel this order?',
            'Confirm Cancellation',
            {
              confirmButtonText: 'Yes, Cancel Order',
              cancelButtonText: 'No, Keep Order',
              type: 'warning'
            }
        );

        cancellingOrder.value = orderId;
        await axios.delete(`/api/order/${orderId}`);
        ElMessage.success('Order cancelled successfully');

        // Refresh orders
        await fetchOrders();
      } catch (error) {
        if (error !== 'cancel') {
          console.error('Error cancelling order:', error);
          ElMessage.error('Failed to cancel order. Please try again later.');
        }
      } finally {
        cancellingOrder.value = null;
      }
    };

    const formatDate = (dateString, showTime = false) => {
      if (!dateString) return 'N/A';

      const date = new Date(dateString);
      const options = {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
      };

      if (showTime) {
        options.hour = '2-digit';
        options.minute = '2-digit';
      }

      return date.toLocaleDateString('en-US', options);
    };

    const formatPrice = (price) => {
      if (!price) return '$0.00';

      return new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD'
      }).format(price);
    };

    const calculateSubtotal = (item) => {
      if (!item.product || !item.product.price) return 0;
      return item.product.price * item.quantity;
    };

    const calculateTotalItems = (orderId) => {
      if (!orderItems.value[orderId]) return 0;

      return orderItems.value[orderId].reduce((total, item) => {
        return total + item.quantity;
      }, 0);
    };

    const truncateText = (text, maxLength) => {
      if (!text) return '';
      return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
    };

    const goToShop = () => {
      // Navigate to shop page - implementation depends on your router setup
      console.log('Navigating to shop page');
    };

    onMounted(() => {
      fetchOrders();
    });

    return {
      orders,
      orderItems,
      orderItemsWithProducts,
      loading,
      loadingItems,
      activeOrders,
      cancellingOrder,
      completedOrders,
      pendingOrders,
      fetchOrders,
      fetchOrderItems,
      handleOrderExpand,
      cancelOrder,
      formatDate,
      formatPrice,
      calculateSubtotal,
      calculateTotalItems,
      truncateText,
      goToShop
    };
  }
};
</script>

<style scoped>
.orders-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header-card {
  margin-bottom: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content h1 {
  margin: 0;
  font-size: 28px;
  color: #303133;
}

.order-stats {
  display: flex;
  gap: 12px;
}

.orders-list {
  margin-top: 20px;
}

.order-item {
  margin-bottom: 16px;
  transition: all 0.3s ease;
}

.order-item:hover {
  transform: translateY(-2px);
}

.order-header {
  display: flex;
  align-items: center;
  width: 100%;
  gap: 16px;
}

.order-id {
  font-weight: bold;
  color: #409eff;
  min-width: 100px;
}

.order-date {
  flex: 1;
  color: #606266;
}

.order-total {
  font-weight: bold;
  margin-left: 16px;
  color: #303133;
}

.order-details {
  padding: 16px 0;
  margin: 10px;
}

.order-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
  color: #606266;
}

.product-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
  margin: 16px 0;
}

.product-card {
  transition: transform 0.2s;
}

.product-card:hover {
  transform: translateY(-4px);
}

.product-card-content {
  display: flex;
  gap: 16px;
}

.product-image {
  width: 120px;
  height: 120px;
  border-radius: 4px;
  object-fit: cover;
  flex-shrink: 0;
}

.image-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 120px;
  height: 120px;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 24px;
}

.product-details {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.product-name {
  margin: 0 0 8px;
  font-size: 16px;
  color: #303133;
}

.product-description {
  margin: 0 0 12px;
  font-size: 14px;
  color: #606266;
  line-height: 1.4;
  flex-grow: 1;
}

.product-price-qty {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-top: auto;
}

.product-price {
  display: flex;
  flex-direction: column;
}

.unit-price {
  font-size: 14px;
  color: #606266;
}

.subtotal {
  font-weight: bold;
  color: #303133;
}

.quantity-tag {
  margin-left: auto;
}

.order-summary {
  background-color: #f8f9fa;
  border-radius: 4px;
  padding: 16px;
  margin: 16px 0;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;
}

.summary-row.total {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #dcdfe6;
  font-weight: bold;
  font-size: 16px;
  color: #303133;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 16px;
}

.loading-items {
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

/* Responsive adjustments */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .order-meta {
    flex-direction: column;
    gap: 8px;
  }

  .order-header {
    flex-wrap: wrap;
  }

  .product-card-content {
    flex-direction: column;
  }

  .product-image {
    width: 100%;
    height: 180px;
  }

  .image-placeholder {
    width: 100%;
    height: 180px;
  }
}
</style>